<?php 

	use think\Db;
	use think\Config;
	use wechatvi\WxCrypt;
	use think\Cache;

	/**
	 * 实例化DOM操作
	 * @date   2018-06-03
	 * @author 董
	 * @return [obj]
	 */
	function dom(){
		return new DOMDocument();
	}

	/**
     * @param string $url
     * @return mixed
     */
    function get($url)
    {
        //初始化
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL,$url);
        // 执行后不直接打印出来
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // 不从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        //执行并获取HTML文档内容
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);
        
        return $output;
    }

	/**
	 * POST请求https接口返回内容
	 * @date   2018-06-03
	 * @param  string $url [请求的URL地址]
	 * @param  string $post [请求的参数]
	 * @author 董
	 * @return  string
	 */
	function post($url, $post='')
	{
	    $curl = curl_init(); // 启动一个CURL会话

	    curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
	    //curl_setopt($curl, CURLOPT_HTTPHEADER,$header); // header
	    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
	    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
	    curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
	    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
	    curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
	    curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
	    curl_setopt($curl, CURLOPT_POSTFIELDS, $post); // Post提交的数据包
	    curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
	    curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
	    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
	    $res = curl_exec($curl); // 执行操作
	    if (curl_errno($curl)) {
	        // echo 'Errno'.curl_error($curl);//捕抓异常
	        return fasle;
	    }
	    curl_close($curl); // 关闭CURL会话
	    return $res; // 返回数据，json格式
	}

	/**
	 * [getAccessToken 获取access_token]
	 * @param  [type] $prem   [description]
	 * @param  [type] $appid  [description]
	 * @param  [type] $secret [description]
	 * @return [type]         [description]
	 */
	function getAccessToken($appid,$secret){
		$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET';
		$data['appid'] = $appid;
		$data['secret'] = $secret;
		$access = post($url,$data);
		$access_token = json_decode($access,true);
		return $access_token['access_token'];
	}

	/**
	 * [getComponentVerifyTicket 获取ComponentVerifyTicket]
	 * @return [type] [description]
	 */
	function getComponentVerifyTicket(){
		//相关配置
        $encodingAesKey = Config::get('encodingAesKey');
        $token = Config::get('token');
        $appId = Config::get('appId');
        $appsecret = Config::get('appsecret');      
        //1.微信推送数据
            // --- 已在推送接口获取
        //2.获取第一步保存的component_verify_ticket  
        $str=file_get_contents('../../wxcode.txt');
        $array = unserialize($str);
        $xmlStr=file_get_contents('../../wxcodexml.xml');
        WxCrypt::BizMsgCrypt($token, $encodingAesKey, $appId);
        //开始解密
        $msg = '';
        $errorCode = WxCrypt::decryptMsg($array['msg_signature'], $array['timestamp'], $array['nonce'], $xmlStr,$msg);
        if($errorCode != 0){
            $data = array(
                'code' => $errorCode,
                'msg'  => '请求错误，请参照错误码进行配置修改，错误编码'.$errorCode
            );
            echo json_encode($data,false);die;
        }
        return $wxContent = simplexml_load_string($msg,'SimpleXMLElement', LIBXML_NOCDATA);
	}
	/**
	 * [getAuthorizerAccessToken 更新返回AuthorizerAccesstoken]
	 * @param  [type] $userId [description]
	 * @return [type]         [description]
	 */
	function getAuthorizerAccessToken($userId){
		// $Itime = Db::table('a_small_program_relation')
  //               ->where(['userId'=>$userId])
  //               ->where('cexpiresIn','GT',time())
  //               ->find();
  //       if(!$Itime){ //过期
        	//获取ComponentVerifyTicket
        	$wxContent = getComponentVerifyTicket();
			$InfoType = $wxContent->InfoType;
	        $ComponentVerifyTicket = $wxContent->ComponentVerifyTicket;
            //3.component_access_token获取
            $tokenApiUrl = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token';
            $data['component_appid'] = Config::get('appId');
            $data['component_appsecret'] = Config::get('appsecret');
            $data['component_verify_ticket'] = (string)$ComponentVerifyTicket;
            $data = json_encode($data);
            $tokenData = post($tokenApiUrl,$data);
            $tokenData = json_decode($tokenData,true);
            if(isset($tokenData['errcode'])){
            	return false;
            }
            $token = (string)$tokenData['component_access_token']; //令牌
            return $token;
        //     $tokenExpires = (string)$tokenData['expires_in'] + time();  //有效期  后续投入使用
        //     //是否存在
        //     $count = Db::table('a_small_program_relation')
        //         ->where(['userId'=>$userId])
        //         ->count();
        //     if($count > 0){//如果存在更新
        //         $a = Db::table('a_small_program_relation')->where(['userId'=>$userId])->update(['componentAccessToken'=>$token,'cexpiresIn'=>$tokenExpires]);
        //     }else{//不存在就新增
        //         Db::table('a_small_program_relation')->insert(['userId'=>$userId,'componentAccessToken'=>$token,'cexpiresIn'=>$tokenExpires]);
        //     }
        // }else{//没有过期
        //     $token = $Itime['componentAccessToken'];
        // }
        // return $token;
	}

	/**
	 * [getauthorizerAccessToken 获取authorizerAccessToken]
	 * @return [type] [description]
	 */
 	function authorizerAccessToken($userId,$biz_id){
 		$appc = Db::table('minipro_copy')->where(['biz_id'=>$biz_id])->find();
 		//是否 缓存
 		if(Cache::get('authorizer_access_token_'.$biz_id)){
 			$actdata['authorizer_access_token'] = Cache::get('authorizer_access_token_'.$biz_id);
 		}else{
 			//刷新令牌
 			$component_access_token = getAuthorizerAccessToken($userId);
			$tokenApiUrl = 'https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token='.$component_access_token;
	        $data['component_appid'] = Config::get('appId');
	        $data['authorizer_appid'] = $appc['appid'];
	        $data['authorizer_refresh_token'] = (string)$appc['refresh_token'];
	        $param = json_encode($data);
	        $tokenData = post($tokenApiUrl,$param);
	        $actdata = json_decode($tokenData,true);
	        if(isset($actdata['errcode'])){
	        	return false;
	        }
	        Db::table('minipro_copy')->where(['biz_id'=>$biz_id])->update([
	        	'refresh_token'=>$actdata['authorizer_refresh_token']
	        ]);	
	        //存储缓存
	        Cache::set('authorizer_access_token_'.$biz_id,$actdata['authorizer_access_token'],7200);
 		}
        $actdata['appid'] = $appc['appid'];
        return $actdata;
	}
?>
